﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Planer.Model;
using Planer.UI.Forms;

namespace Planer.UI.Controls
{
    public partial class UserPanel : UserControl
    {
        private user currentUser = null;

        public user CurrentUser
        {
            get { return currentUser; }
            set 
            { 
                currentUser = value;
                if (currentUser == null)
                {
                    return;
                }

                labelName.Text = currentUser.name;
                labelEmail.Text = currentUser.email;
                textBoxNewMail.Text = currentUser.email;
            }
        }


        public UserPanel()
        {
            InitializeComponent();

            panelChangeMail.Location = new Point(labelEmail.Location.X, labelEmail.Location.Y - panelChangeMail.Margin.Top);
        }

        private void labelEmail_DoubleClick(object sender, EventArgs e)
        {
            
            panelChangeMail.Visible = true;
            textBoxNewMail.Focus();
            labelEmail.Visible = false;
        }

        private void hideChangeEmailPanel(object sender, EventArgs e)
        {            
            panelChangeMail.Visible = false;
            labelEmail.Text = currentUser.email;
            labelEmail.Visible = true;
        }

        private void textBoxNewMail_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    currentUser.email = textBoxNewMail.Text;
                    ModelResult mr = UserModel.GetInstance().SaveOrUpdateUser(currentUser);
                    if (mr.Status == OperationStatusType.ERROR)
                    {
                        MessageBoxUtils.ShowErrorBox(mr.FirstError);
                        return;
                    }

                    hideChangeEmailPanel(sender, null);
                    break;
                case Keys.Escape:
                    hideChangeEmailPanel(sender, null);
                    break;
            }                        
        }

        private void buttonChangePassword_Click(object sender, EventArgs e)
        {
            NewPasswordForm frm = new NewPasswordForm(currentUser);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                currentUser.password_hash = frm.NewPassword;
                UserModel.GetInstance().SaveOrUpdateUser(currentUser);
            }
        }

    }
}
